﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Psm.PubSub.StateCache;
using Psm.PubSub.Serialization;
using Psm.Util;

namespace Psm.PubSub.Messaging
{
    public class SchemaMessage : PubSubMessage
    {
        public  Schema Schema { get; private set;}

        public override PubSubMessageType MessageType
        {
            get 
            { 
                return PubSubMessageType.SCHEMA_MESSAGE; 
            }
        }

        public SchemaMessage(ByteBuffer payload)
        {
            MessageDeserializer serializer = new MessageDeserializer(payload);

            this.Schema = new Schema(serializer.GetField());
            while (serializer.HasMore())
            {
                string name;
                string isKey;
                string type;
                serializer.GetTuple(out name, out isKey, out type);
                Schema.AddField(new SchemaField(name, type, null, bool.Parse(isKey), Schema.Fields.Count));
            }
        }

        public SchemaMessage(Schema schema)
        {
            this.Schema = schema;
        }

        public override bool Serialize(ByteBuffer buffer)
        {
            MessageSerializer serializer = new MessageSerializer(PubSubMessageType.SCHEMA_MESSAGE, buffer);
            if (Schema != null)
            {
                if( !serializer.AppendField(Schema.Topic) ) return false;
                for (int index = 0; index < Schema.Fields.Count; index++)
                {
                    SchemaField field = Schema.Fields[index];
                    if( !serializer.AppendTuple(field.Name, field.IsKey.ToString(), field.Type.ToString()) ) return false;
                }
            }
            return true;
        }
    }
}
